<script setup>
import { ref, onMounted, onUnmounted } from "vue";
import * as echarts from "echarts";
import { shouyeIndex } from "@/api";
const chartRef = ref(null);
let myChart = null;

onMounted(async () => {
  const res = await shouyeIndex();
  // console.log(res);

  // 1. 初始化图表
  myChart = echarts.init(chartRef.value);

  // 设置图表配置
  const option = {
    title: {
      text: "健身房管理系统参数统计图",
      left: "center",
    },
    tooltip: {
      trigger: "item",
      formatter: "{a} <br/>{b}: {c} ({d}%)",
    },
    series: [
      {
        name: "总计",
        type: "pie",
        radius: "70%",
        data: [
          { value: res.all, name: "健身房总人数" },
          { value: res.huiyuanshu, name: "会员数" },
          { value: res.qicaishu, name: "器材数" },
          { value: res.subjectshu, name: "课程数" },
        ],
        label: {
          show: true,
          // 自定义标签格式：显示名称+数值+百分比
          formatter: "{b}: {c} ({d}%)",
        },
      },
    ],
  };

  // 3. 应用配置项
  myChart.setOption(option);

  // 4. 监听窗口大小变化，自适应图表
  window.addEventListener("resize", handleResize);
});

onUnmounted(() => {
  // 组件卸载时销毁图表实例并移除事件监听
  if (myChart) {
    myChart.dispose();
    myChart = null;
  }
  window.removeEventListener("resize", handleResize);
});

const handleResize = () => {
  myChart && myChart.resize();
};
</script>

<template>
  <div class="index" style="width: 100%" ref="chartRef"></div>
</template>

<style scoped lang="scss">
.index {
  width: 100%;
  height: 100%;
  // background-color: skyblue;
}
</style>
